const Router = require('koa-router');
const router = new Router();
const { setToken, getToken } = require('./libs/common')

//跨域
router.all('(.*)', async (ctx, next) => {
    // ctx.set('Access-Control-Allow-Origin', '*');
    // ctx.set('Access-Control-Allow-Methods', '*');
    // ctx.set('Access-Control-Allow-Headers', '*');
    // ctx.session.access_token = null;
    if (ctx.method == 'OPTIONS') {
        ctx.body = 'ok';
    } else {
        ctx.access_token = ctx.headers.authorization
        ctx.assert = function (cord, msg) {
            if (!cord) {
                ctx.status = 400;
                ctx.body = { msg: 'invaild argument' };

                throw {
                    status: 400,
                    body: { msg }
                };
            }
        };
        ctx.errcode = function (errcode, msg) {
            if (errcode) {
                throw {
                    status: errcode,
                    body: { msg }
                };
            }
        }

        try {
            await next();
        } catch (e) {
            console.log(e)
            const token = getToken();
            if (e.status) {
                switch (e.status) {
                    case 40001:
                        ctx.status = 401;
                        if (!!token && JSON.parse(token).expires_in > new Date().getTime()) {
                            setToken(token);
                        } else {
                            setToken('');
                        }
                        
                        ctx.body = e.body;
                        break;
                    case 40014:
                        ctx.status = 401;
                        if (!!token && JSON.parse(token).expires_in > new Date().getTime()) {
                            setToken(token);
                        } else {
                            setToken('');
                        }
                        ctx.body = e.body;
                        break;
                    case 42001:
                        ctx.status = 401;
                        if (!!token && JSON.parse(token).expires_in > new Date().getTime()) {
                            setToken(token);
                        } else {
                            setToken('');
                        }
                        ctx.body = e.body;
                        break;
                    default:
                        ctx.status = e.status;
                        ctx.body = e.body;
                        break;
                }
            } else {
                ctx.status = 500;
                ctx.body = 'Internal Server Error';
            }
        }
    }
});

router.use('/upload', require('./api/upload'))
router.use('/api', require('./api/index'))
// router.use('/store', require('./api/store'));
// router.use('/user', require('./user'));
// router.use('/blog', require('./blog'));

module.exports = router.routes();